{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05d2d66f-323e-40c6-9b2a-bebcf25c4a0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "from mlxtend.frequent_patterns import apriori, association_rules\n",
    "\n",
    "df = pd.read_excel('./222/餐厅数据.xlsx')\n",
    "#print(df.head)\n",
    "\n",
    "# 转换菜品格式\n",
    "transactions = df['菜品'].str.split(',').to_list()\n",
    "\n",
    "# 标准化\n",
    "te = TransactionEncoder()\n",
    "te_ary = te.fit(transactions).transform(transactions)\n",
    "df_encoded = pd.DataFrame(te_ary, columns=te.columns_)\n",
    "\n",
    "# print(df_encoded.head())\n",
    "# 使用apriori进行分析\n",
    "frequent_itemsets = apriori(df_encoded, min_support=0.1, use_colnames=True)\n",
    "frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)\n",
    "\n",
    "# 选择二项集查看\n",
    "print(frequent_itemsets[frequent_itemsets.itemsets.apply(lambda x: len(x) == 2)])\n",
    "\n",
    "# 生成关联规则\n",
    "rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.1)\n",
    "rules = rules.sort_values(by=['lift'], ascending=False)\n",
    "\n",
    "# 保存模型结果\n",
    "frequent_itemsets.to_pickle(\"frequent_itemsets.pkl\")\n",
    "rules.to_pickle(\"rules.pkl\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51e56e7d-d4d8-43b3-9a6a-3a2629868a06",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
